import asyncio
from settings import settings

import aiohttp
from ujson import loads


async def get_token(code, session):
    url = 'https://gw.open.1688.com/openapi/http/1/system.oauth2/getToken/' + settings["app_key"]

    params = {
        'grant_type': 'authorization_code',
        'need_refresh_token': 'true',
        'client_id': settings["app_key"],
        'client_secret': settings["app_secret"],
        'redirect_uri': settings["app_callback_url"] + '/get/authorization/',
        'code': code
    }

    async with session.post(url, params=params, timeout=5) as resp:
        status_code = resp.status
        text = await resp.text()

    return status_code, loads(text)


async def main(access_token):
    session = aiohttp.ClientSession()

    try:
        status, code = await get_token(access_token, session)
        print(code)

    finally:
        await session.close()


if __name__ == '__main__':
    access_token = "3f664cbb-1496-42da-875e-0b14f2b748cf"
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(access_token))
